/**
 * Created by zhulizhe on 2017/9/5.
 */
import React, {Component} from 'react';
import {
    Text,
    TextInput,
    View,
    TouchableOpacity,
    Image,
    ScrollView,
    Dimensions
} from 'react-native';
import Contant from "../../../js/Contant";
import RequestUtil from '../../../js/util/NetUtil'
import {observer} from "mobx-react";
import {observable, computed} from 'mobx'
import ImagePicker from 'react-native-image-picker';
import {PraiseOrder} from '../../../js/order/OrderNet'
import {Star} from "../../../js/home/Home";
import {Loading, EasyLoading} from 'react-native-easy-loading';

const {width} = Dimensions.get('window');
// 商品评论
let ProductCommentScore = {
    score: 10,
    comment: '',
    imgUrls: []
};

let DeliveryerCommentM = {
    comment: '',
    deliveryerId: 0,
    score: 10
};
let ShopCommentM = {
    content: '',
    imageList: [],
    score: 10
};
const options = {
    title: '选择图片',
    cancelButtonTitle: '取消',
    chooseFromLibraryButtonTitle: '相册选取',
    takePhotoButtonTitle: '拍照',
    storageOptions: {
        skipBackup: true,
        path: 'images'
    },
    quality: 0.5
}

const UpImage = (filePath) => {
    return new Promise((res, rej) => {
        RequestUtil.uploadImage([filePath], (resp) => {
            LOG('上传图片结果-------------'+JSON.stringify(resp));
            if (resp != null) {
                if (resp.status && resp.status == 500) {
                    res(resp);
                } else if (resp.ret_msg == '上传成功') {
                    res(resp.head_img);
                }
            }
        })
    })
}

//图片选择
const PicturePicker = ({onChange, uploadBegin, uploadEnd}) => {
    const images = [''];
    const currentImages = observable(images);
    const onPress = () => {
        ImagePicker.showImagePicker(options, response => {
            if(response.uri==null)return;
            let source = {uri: response.uri};
            uploadBegin();
            UpImage(source).then(imageUrl => {
                uploadEnd();
                if(imageUrl.message!=null)return;
                currentImages.push(imageUrl);
                onChange(imageUrl);
            });
        })
    };
    const ImagesCom = observer(() => {
        let images = currentImages.map((imgUrl, index) => {
            return (<TouchableOpacity key={index}
                                      onPress={onPress}>
                <Image resizeMode="cover"
                       key={index}
                       style={{marginRight: 12, width: 60, height: 60}}
                       source={imgUrl.length == 0 ? require('../../../luoasserts/me/btn_add-photo.png') : {uri: imgUrl}}/>
            </TouchableOpacity>)
        })

        return <ScrollView
            style={{
                flexWrap: 'wrap',
                flexDirection: 'row',
                height: 60
            }}
            horizontal={true}>
            {images}
        </ScrollView>
    })

    return <ImagesCom/>
}

//商品评价
@observer
class ProductPraise extends Component {
    @observable imageUrls = [];

    static productPraiseScore(score) {
        ProductCommentScore.score = score;
        ShopCommentM.score = score;
    }

    uploadBegin() {
        this.props.uploadBegin();
    }

    uploadEnd() {
        this.props.uploadEnd(this.imageUrls);
    }

    render() {
        return <View>
            <View style={PraiseStyle.sepViewS}/>
            <View style={PraiseStyle.lineViewS}/>
            <View style={PraiseStyle.starsBackS}>
                <Text style={PraiseStyle.infoTextS}>商品评价</Text>
                <Star
                    onChange={(score) => {
                        ProductPraise.productPraiseScore(2*score);
                    }}/>
            </View>
            <View style={PraiseStyle.lineViewS}/>
            <View style={{backgroundColor: 'white', height: 160}}>
                <TextInput style={PraiseStyle.praiseTextInputS}
                           multiline={true}
                           placeholder='评价一下这件宝贝吧'
                           maxLength={150}
                           onChangeText={(text) => {
                               ProductCommentScore.comment = text
                           }}/>
                <View style={PraiseStyle.productPicS}>
                    <PicturePicker
                        uploadBegin={this.uploadBegin.bind(this)}
                        uploadEnd={this.uploadEnd.bind(this)}
                        onChange={(imageUrl => {
                            this.imageUrls.push(imageUrl);
                        })}/>
                </View>
            </View>
            <View style={PraiseStyle.lineViewS}/>
        </View>
    }
}

//配送评价
class DeliveryPraise extends Component {
    static deliveryPraiseScore(score) {
        DeliveryerCommentM.score = score;
    }

    render() {
        return <View>
            <View style={PraiseStyle.sepViewS}/>
            <View style={PraiseStyle.lineViewS}/>
            <View style={PraiseStyle.starsBackS}>
                <Text style={PraiseStyle.infoTextS}>评价配送评价</Text>
                <Star
                    onChange={(score) => {
                        DeliveryPraise.deliveryPraiseScore(score);
                    }}/>
            </View>
            <View style={PraiseStyle.lineViewS}/>
            <View style={{flex: 1, flexDirection: 'row', backgroundColor: 'white', height: 160}}>
                <TextInput style={PraiseStyle.praiseTextInputS}
                           multiline={true}
                           placeholder='评价一下送水工的服务吧'
                           maxLength={150}
                           onChangeText={(text) => {
                               DeliveryerCommentM.comment = text
                           }}/>
            </View>
            <View style={PraiseStyle.lineViewS}/>
        </View>
    }
}


class Bottom extends Component {
    async praiseOrder() {
        this.props.praiseClick();
    }

    render() {
        const backS = {
            position: 'absolute',
            justifyContent: 'center',
            alignItems: 'center',
            left: 0,
            right: 0,
            bottom: 0,
            height: 50,
            backgroundColor: 'white'
        };
        return <View style={backS}>
            <TouchableOpacity onPress={this.praiseOrder.bind(this)}>
                <Text style={{color: '#4dc0ff', fontSize: 14}}>发表评价</Text>
            </TouchableOpacity>
        </View>
    }
}

export default class OrderPraiseLuo extends Component {
    static navigationOptions = {
        title: '评价',
    };

    constructor(props) {
        super(props)
        this.imageUrls = [];
    }

    uploadBegin() {
        EasyLoading.show('正在上传中');
    }

    uploadEnd(imageUrls) {
        this.imageUrls = imageUrls;
        EasyLoading.dismis();
    }


    async praiseClick() {
        let {shopId, orderId, deliveryId, productModels} = this.props.navigation.state.params;
        let productCommentModels = productModels.map((productM, index) => {
            return {
                comment: ProductCommentScore.comment,
                imageUrlList: this.imageUrls,
                productItemId: productM.productItemId,
                score: ProductCommentScore.score
            };
        });
        DeliveryerCommentM.deliveryerId = deliveryId;
        let scoreParam = {
            commentModel:{
                deliveryerCommentModel: DeliveryerCommentM,
                orderId: orderId,
                productCommentModels: productCommentModels,
                shopCommentModel: ShopCommentM,
                shopId: shopId
            }
        };
        EasyLoading.show('正在发表...');
        let praise = await PraiseOrder(scoreParam);
        if (praise) {
            this.props.navigation.goBack();
        }
        EasyLoading.dismis();
    }

    render() {
        return <View style={{
            flex: 1,
            backgroundColor: Contant.GRAYBGCOLOR,
            flexDirection: 'row',
        }}>
            <ScrollView style={{flex: 1, backgroundColor: Contant.GRAYBGCOLOR}}>
                <ProductPraise
                    uploadBegin={this.uploadBegin.bind(this)}
                    uploadEnd={this.uploadEnd.bind(this)}
                />
                <DeliveryPraise/>
            </ScrollView>
            <Bottom
                praiseClick={this.praiseClick.bind(this)}
            />
            <Loading/>
        </View>
    }
}

const PraiseStyle = {
    lineViewS: {
        flexDirection: 'row',
        backgroundColor: 'rgba(227,227,227,1)',
        height: 0.5
    },
    sepViewS: {
        flexDirection: 'row',
        backgroundColor: 'rgba(241,241,243,1)',
        height: 14
    },
    starsBackS: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: 'white',
        height: 60
    },
    infoTextS: {
        marginLeft: 12,
        fontSize: 14.5,
        color: 'rgba(51,51,51,1)'
    },
    praiseTextInputS: {
        marginLeft: 12,
        marginRight: 12,
        marginTop: 10,
        width: width - 24,
        height: 66,
        fontSize: 13.5,
        color: 'rgba(51,51,51,1)'
    },
    productPicS: {
        flexDirection: 'row',
        marginLeft: 12,
        marginRight: 12,
        marginTop: 12,
        width: width - 24,
        height: 84
    }
};
